<template>
  <view class="invitePeople">
    <view class="topSearch">
      <view class="inputBox">
        <image src="../../static/icons/search.png" class="icon"></image>
        <input
          type="text"
          class="inputText"
          v-model="searchContent"
          placeholder="输入想要邀请的人员名称"
          @confirm="handleSearchPeople"
        />
      </view>
    </view>
    <view class="userList" v-if="searchFlag">
      <view class="title">查询结果</view>
      <SearchPeopleList @invitePeople="handleInvitePeople" />
    </view>
    <view class="content" v-else>
      <view class="history">
        <view class="head">
          <view class="title">历史搜索</view>
          <image
            src="../../static/icons/trash.png"
            class="icon"
            @click="clearHistory"
          ></image>
        </view>

        <view class="historyList">
          <view
            class="history-item"
            v-for="(item, index) in historyList"
            @click="handleClickHistory(item)"
            :key="index"
            >{{ item }}</view
          >
        </view>
      </view>
      <view class="newList">
        <view class="title">最新人员</view>
        <SearchPeopleList @invitePeople="handleInvitePeople" />
      </view>
    </view>
  </view>
</template>

<script>
import SearchPeopleList from "./components/SearchPeopleList.vue";
import { TeamMessage } from "../../utils/messageController";
export default {
  components: {
    SearchPeopleList,
  },
  data() {
    return {
      currentTeam: {},
      historyList: [],
      searchContent: "",
      tempUserId: "", // 缓存邀请的id，禁止重复邀请
      searchFlag: false,
    };
  },

  onLoad(options) {
    this.currentTeam = JSON.parse(decodeURIComponent(options.teamDetail));
    this.historyList = JSON.parse(wx.getStorageSync("searchInvite") || "[]");
  },

  mounted() {
    this.$store.dispatch("m_search/getSearchUserList", {
      type: "get",
      page: 0,
      limitCount: 5,
    });
  },
  watch: {
    searchFlag(newValue) {
      if (newValue) {
        this.saveSearchToCache(this.searchContent);
        this.$store.dispatch("m_search/getSearchUserList", {
          type: "query",
          name: this.searchContent,
        });
      }
    },

    searchContent(newValue) {
      if (!newValue.length) {
        this.searchFlag = false;
      }
    },
  },
  methods: {
    handleClose() {
      this.drawerFlag = false;
    },

    handleSearchPeople() {
      this.searchFlag = true;
    },
    // 邀请加入逻辑
    async handleInvitePeople(id) {
      if (id === this.tempUserId) {
        uni.showToast({
          title: "已发出过邀请",
          icon: "error",
        });
        return;
      }
      console.log("check:",id,this.currentTeam);
      if (this.currentTeam.userList.includes(id)) {
        
        uni.showToast({
          title: "已是队伍成员",
          icon: "error",
        });
        return;
      }
      this.tempUserId = id; // 缓存发出邀请的id
      const messageBox = new TeamMessage();
      const message = messageBox.messageForInvite({
        teamName: this.currentTeam.title,
        receiveId: id,
        teamId: this.currentTeam._id,
        inviteName: this.currentTeam.author.nickName,
      });
      console.log("inviteMessage:",message);
      try {
        await this.$store.dispatch("m_message/sendMessage", message);
        uni.showToast({
          title: "已发送邀请",
          icon: "success",
        });
      } catch (err) {
        console.log("invite error:", err);
        uni.showToast({
          title: "发送失败",
          icon: "error",
        });
      }
    },

    // 点击历史记录
    handleClickHistory(content) {
      this.searchContent = content;
      this.handleSearchPeople();
    },

    // 清空历史记录
    clearHistory() {
      wx.showModal({
        title: "确认要清空历史记录吗?",
        success: () => {
          this.historyList = [];
          wx.setStorageSync("searchInvite", JSON.stringify([]));
        },
      });
    },

    // 记录保存至缓存
    saveSearchToCache(content) {
      const search = JSON.parse(wx.getStorageSync("searchInvite") || "[]");
      if (search.includes(content)) return;
      search.push(content);
      wx.setStorageSync("searchInvite", JSON.stringify(search));
      this.historyList = search;
    },
  },
};
</script>

<style lang="scss" scoped>
.invitePeople {
  width: 100vw;
  height: 100%;
  background-color: #fff;

  .title {
    font-weight: 700;
    font-size: 34rpx;
  }
  .topSearch {
    width: 95vw;
    margin: 0 auto;
    padding: 20rpx 0;
    display: flex;
    align-items: center;
    .inputBox {
      display: flex;
      align-items: center;
      background-color: #f0f0f0;
      padding: 10rpx 20rpx;
      border-radius: 5rpx;
      flex: 1;
    }

    .icon {
      width: 40rpx;
      height: 40rpx;
      margin-right: 15rpx;
    }
  }

  .head {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .icon {
      width: 30rpx;
      height: 30rpx;
    }
  }
  .history {
    padding: 15rpx;
    .historyList {
      margin-top: 20rpx;
      display: flex;
      flex-wrap: wrap;
      .history-item {
        margin: 0 15rpx 15rpx 0;
        background-color: #f0f0f0;
        border-radius: 5rpx;
        color: #333333;
        font-size: 24rpx;
        padding: 10rpx;
      }
    }
  }
  .userList,
  .newList {
    padding: 15rpx;
  }
  .drawerContent {
    width: 70vw;
    height: 100vh;
  }
}
</style>
